<!DOCTYPE html>
<html lang="en">
<#include "../common/scripts.html">
<#include "../common/scripts_add.html">
<body >
<style>
    .table-main-2 {
        table-layout: fixed;
        word-break: break-all;
    }

    .table-main-2 th {
        border: 1px solid #DBF4FF;
        color: #0CB3FE;
    }

    .table-main-2 td {
        border: 1px solid #ccc;
    }

    .table-main-2 tr td:nth-child(odd) {
        text-align: center;
        width: 10% !important;
    }

    .table-main-2 tr td:nth-child(even) {
        width: 30% !important;
    }
    #magicsuggest{
        border-radius:0px;
        border:none;
    }
    .data-list-2>.dataTables_wrapper>.row:nth-child(2) {
        display: none;
    }
</style>
<div class="page-content" style="min-height:500px;">
    <form action="" method="post" id="editForm" class="form-horizontal">
    <div class="fh-subtitle">用户信息</div>
        <input type="text"  id="id"  name="id" value="${user.id!}" class="hide">
        <table class="table-main" style="width: 80% !important; border-collapse:collapse;">
            <tr>
                <td style="width: 10%;"><#if (user.id!) == ''><span class="required-flag">*</span></#if><span>所属公司</span></td>
                <td>
                    <div class="input-group" style="width: 100%;">
                        <input type="text" class="form-control" id="companyName" name="companyName"  value="${user.companyName!}"style="border: 0; " placeholder="请选择" readonly />
                        <#if (user.id!) == ''>
                        <span id="companyMenu"  class="input-group-btn btn btn-default" style="border-left: 1px solid #ccc;font-size: 13px; border: 0; border-radius:0px;">
                        <i class="fa fa-search"></i></span>
                        </#if>
                    </div>
                    <input type="hidden" id = "companyCode" name = "companyCode" value="${user.companyCode!}">
                </td>
                <td style="width: 10%;"><#if (user.id!) == ''><span class="required-flag">*</span></#if><span>用户名</span></td>
                <td style="position: relative;">
                    <input  class="form-control-gx" value="${user.username!}" name="username" id="username" autocomplete="off" <#if (user.id!) != '' >readonly</#if>/>
                </td>
            </tr>
            <tr>
                <td><span class="required-flag">*</span><span>工号</span></td>
                <td><input type="text" class="form-control-gx"  value="${user.userCode!}" name="userCode" id="userCode" autocomplete="off"></td>
                <td style="width: 10%;"><span class="required-flag">*</span><span>姓名</span></td>
                <td style="position: relative;">
                    <input  class="form-control-gx" value="${user.name!}" name="name" id="name" autocomplete="off"/>
                </td>
            </tr>
           <!-- <tr>
                <td><span class="required-flag">*</span><span>角色</span></td>
                <td  colspan="3">
                    <textarea id="magicsuggest"></textarea>
                </td>
            </tr>-->
            <tr>
                <td><span>说明</span></td>
                <td  colspan="3">
                    <input  class="form-control-gx" type="text" name="remark" id = "remark" value="${user.remark!}" style="height: 50px;" autocomplete="off">
                </td>
            </tr>
        </table>
    <div class="fh-subtitle">分配角色
        <span class="btn btn-sm glyphicon glyphicon-plus" onclick="addUserRole()" style="color: #fff;font-size:12px;padding:2px 8px;">新增</span>
    </div>
    <div class="data-list-2" style="width: 80%!important;padding: 0px;">
        <table id="userRoleTable" class="eamtable">
            <thead>
            <tr style="background: #ECEFF0; color: #777;">
                <th>ID</th>
                <th>角色名称</th>
                <th>角色编码</th>
                <th>应用名称</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    <div class="fh-subtitle">分配岗位
        <span class="btn btn-sm glyphicon glyphicon-plus" onclick="addUserPostGroup()" style="color: #fff;font-size:12px;padding:2px 8px;">新增</span>
    </div>
    <div class="data-list-2" style="width: 80%!important;padding: 0px;">
        <table id="userPostGroupTable" class="eamtable">
            <thead>
            <tr style="background: #ECEFF0; color: #777;">
                <th>ID</th>
                <th>岗位名称</th>
                <th>岗位编码</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    <div class="text-center" style="width: 80%; margin-bottom: 50px;">
        <span class="model-btn" onclick="submit()" style="width:80px;">保存</span>
    </div>
</div>

</form>
<script>
    var userRoleTable = $("#userRoleTable");
    var userPostGroupTable = $("#userPostGroupTable");
    $(function(){
        var id = '${user.id!}';
        var username = '${user.username!}';
        //分配角色---方式一
        /*$.ajax({
            url : "/role/listRoles",
            type : "POST",
            datatype : "json",
            data:{"username":username},
            success : function(data) {
               /!* if(data.data && data.data.length > 0){
                    data.data.forEach(function(v,index){
                        arrays.push(data.data[index].roleName);
                    })
                }*!/
                $('#magicsuggest').magicSuggest({
                    data: data.data.roleAll, //数据源
                    cls: 'sfl-msg',
                    allowFreeEntries: false, //不允许输入不匹配的
                    maxSelection: 1000, //最多可以选择几个
                    queryParam: 'qiyebox',
                    placeholder: '请选择', //提示
                    displayField: 'roleName',
                    valueField: 'id',
                    useZebraStyle: true,
                    beforeSend:function () {
                        debugger;
                    }
                });
                if(!isEmpty(id)){
                    $('#magicsuggest').magicSuggest().setSelection(data.data.userRoleList);
                }
            },
            error : function(data) {
                js.showMessage("请求异常！","","error",1500)
            }
        });*/
        //分配角色---方式二
        userRoleTable.dataTable({
            aLengthMenu: [10000],
            bLengthChange: false,
            bSort: false,
            columns: [
                {data: "id", title: "ID",visible:false},
                {data: "roleName", title: "角色名称"},
                {data: "roleCode", title: "角色编码"},
                {data: "applicationName", title: "应用名称"},
                {
                    data: null,
                    title: "操作",
                    render: function () {
                        return '<span class="btn btn-xs glyphicon glyphicon-trash" onclick="remove_userRole_table_row(this)" style="background-color:rgba(0,0,0,0); color: rgb(221, 90, 67)"></span>';
                    }
                }
            ],
            "language": {
                "url": "${static}/plugin/datatable/media/i18n/zh_cn.json"
            },
            searching: false,
            "paging": false,
            fnInitComplete: function (oSettings, json) {
                //console.log( 'DataTables 初始化完毕' );
                sys.initMenuPower();
                $.ajax({
                    url : "${ctx}/user/getRoleByUserId",
                    type : "POST",
                    datatype : "json",
                    data : {"userId":"${user.id!}"},
                    success : function(data) {
                        if (data.success) {
                            if (isEmpty(data.data)) {
                                rows = [];
                            }
                            var datas = userRoleTable.DataTable().data();
                            var map = iUtils.toKMap(datas, "id");
                            for (var i = 0; i < data.data.length; i++) {
                                if (map[data.data[i].id]) {
                                    data.data.splice(i, 1);
                                    i--;
                                }
                            }
                            userRoleTable.DataTable().rows.add(data.data).draw();
                        } else {
                            sys.topmsg(data.message);
                        }
                    },
                    error : function(data) {
                        js.showMessage("请求异常！","","error",1500)
                    }
                });
            },
            "sDom": '<"row"<"col-sm-12"t><"clear">><"row"<"col-sm-3"l><"col-sm-3"i><"col-sm-6"p><"clear">>',//改变搜索框的位置
        });


        //分配岗位
        userPostGroupTable.dataTable({
            aLengthMenu: [10000],
            bLengthChange: false,
            bSort: false,
            columns: [
                {data: "id", title: "ID",visible:false},
                {data: "postName", title: "岗位名称"},
                {data: "postCode", title: "岗位编码"},
                {
                    data: null,
                    title: "操作",
                    render: function () {
                        return '<span class="btn btn-xs glyphicon glyphicon-trash" onclick="remove_userPostGroup_table_row(this)" style="background-color:rgba(0,0,0,0); color: rgb(221, 90, 67)"></span>';
                    }
                }
            ],
            "language": {
                "url": "${static}/plugin/datatable/media/i18n/zh_cn.json"
            },
            searching: false,
            "paging": false,
            fnInitComplete: function (oSettings, json) {
                //console.log( 'DataTables 初始化完毕' );
                sys.initMenuPower();
                $.ajax({
                    url : "${ctx}/user/getPostGroupByUserId",
                    type : "POST",
                    datatype : "json",
                    data : {"userId":"${user.id!}"},
                    success : function(data) {
                        if (data.success) {
                            if (isEmpty(data.data)) {
                                rows = [];
                            }
                            var datas = userPostGroupTable.DataTable().data();
                            var map = iUtils.toKMap(datas, "id");
                            for (var i = 0; i < data.data.length; i++) {
                                if (map[data.data[i].id]) {
                                    data.data.splice(i, 1);
                                    i--;
                                }
                            }
                            userPostGroupTable.DataTable().rows.add(data.data).draw();
                        } else {
                            sys.topmsg(data.message);
                        }
                    },
                    error : function(data) {
                        js.showMessage("请求异常！","","error",1500)
                    }
                });
            },
            "sDom": '<"row"<"col-sm-12"t><"clear">><"row"<"col-sm-3"l><"col-sm-3"i><"col-sm-6"p><"clear">>',//改变搜索框的位置
        });

    });

    function submit() {
        if(isEmpty_byJqObj($("#companyName"))){
            sys.topmsg("所属公司不能为空");
            return false;
        }
        if(isEmpty_byJqObj($("#username"))){
            sys.topmsg("用户名不能为空");
            return false;
        }
        if(isEmpty_byJqObj($("#userCode"))){
            sys.topmsg("工号不能为空");
            return false;
        }
        if(isEmpty_byJqObj($("#name"))){
            sys.topmsg("姓名不能为空");
            return false;
        }
        /*var roleIdArr=$('#magicsuggest').magicSuggest().getValue();
        if(isEmpty(roleIdArr)){
            sys.topmsg("权限不能为空");
            return false;recordsTotal
        }*/
        /*var userPostGroupRows  = userPostGroupTable.DataTable().page.info().recordsTotal;
        if(userPostGroupRows>1){
            sys.topmsg("请选择一条岗位数据");
            return false;
        }*/
        //角色
        var userRoleTrs = userRoleTable.fnGetNodes(); //fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
        var userRoleIdArr = [];
        for (var i = 0; i < userRoleTrs.length; i++) {
            var trData = userRoleTable.fnGetData(userRoleTrs[i]);
            userRoleIdArr.push(trData.id);
        }
        //岗位
        var userPostGroupTrs = userPostGroupTable.fnGetNodes(); //fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
        var userPostGroupIdArr = [];
        for (var i = 0; i < userPostGroupTrs.length; i++) {
            var trData = userPostGroupTable.fnGetData(userPostGroupTrs[i]);
            userPostGroupIdArr.push(trData.id);
        }
        $.ajax({
            url : "${ctx}/user/saveOrUpdate",
            type : "POST",
            datatype : "json",
            data : $('#editForm').serialize()+"&"+$.param({'roleIds':userRoleIdArr.join(",")})+"&"+$.param({'postGroupIds':userPostGroupIdArr.join(",")}),
            success : function(res) {
                if (res.success) {
                    js.showMessage(res.data,"","success",1500)
                    js.closeCurrentTabPage(function(contentWindow){
                        contentWindow.reload();
                    });
                } else {
                    sys.topmsg(res.message);
                }
            },
            error : function(data) {
                js.showMessage("请求异常！","","error",1500)
            }
        });
    }
    //获取公司
    $("#companyMenu").click(function () {
        PullDownTree_obj.init("${ctx}/company/findCompanyIdTree",
            "#companyName", "", "#companyCode", false, "", "", function(treeId, treeNode) {
                if(treeNode.type=="1"){
                    $("#companyName").val(treeNode.name);
                    $("#companyCode").val(treeNode.value);
                    $("#ztree-container").hide();
                    return false;
                }
            });
    })
    /*********
     * 新增用户角色
     */
    function addUserRole() {
        var id = $("#id").val();
        var nTrs = userRoleTable.fnGetNodes(); //fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
        var arr = [];
        for (var i = 0; i < nTrs.length; i++) {
            var trData = userRoleTable.fnGetData(nTrs[i]);
            arr.push(trData.id);
        }
        window1(null, "选择角色", "${ctx}/user/selectUserRole?roleIdNotIn=" + arr.join(",") + "&userId=" + id
            + "&id=" + id, "900px", "500px", "");
       // showLayerWindow(null, "选择角色", "selectUserRole", ['800px', '500px'], ['10px'], false);
    }
    function addSubUserRoleRows(rows) {
        if (isEmpty(rows)) {
            rows = [];
        }
        var datas = userRoleTable.DataTable().data();
        var map = iUtils.toKMap(datas, "id");
        for (var i = 0; i < rows.length; i++) {
            if (map[rows[i].id]) {
                rows.splice(i, 1);
                i--;
            }
        }
        userRoleTable.DataTable().rows.add(rows).draw();
    }
    //分配角色》删除一行信息。
    function remove_userRole_table_row(e) {
        var row = userRoleTable.DataTable().row($(e).parents('tr'));
        row.remove().draw();
    }

    /*********
     * 新增用户岗位
     */
    function addUserPostGroup() {
        if(isEmpty_byJqObj($("#companyCode"))){
            sys.topmsg("请先选择所属公司");
            return false;
        }
        var id = $("#id").val();
        var nTrs = userPostGroupTable.fnGetNodes(); //fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
        var arr = [];
        for (var i = 0; i < nTrs.length; i++) {
            var trData = userPostGroupTable.fnGetData(nTrs[i]);
            arr.push(trData.id);
        }
        //window1(null, "选择岗位", "${ctx}/user/selectUserPostGroup?postGroupIdNotIn=" + arr.join(",") + "&companyCode=" + $("#companyCode").val(), "900px", "500px", "");
        window1(null, "选择岗位", "${ctx}/user/selectUserPostGroupByTree?postGroupIdNotIn=" + arr.join(",") + "&companyCode=" + $("#companyCode").val(), "300px", "400px", "");
        // showLayerWindow(null, "选择角色", "selectUserRole", ['800px', '500px'], ['10px'], false);
    }
    function addSubUserPostGroup(rows) {
        if (isEmpty(rows)) {
            rows = [];
        }
        var datas = userPostGroupTable.DataTable().data();
        var map = iUtils.toKMap(datas, "id");
        for (var i = 0; i < rows.length; i++) {
            if (map[rows[i].id]) {
                rows.splice(i, 1);
                i--;
            }
        }
        userPostGroupTable.DataTable().rows.add(rows).draw();
    }

    //分配岗位》删除一行信息。
    function remove_userPostGroup_table_row(e) {
        var row = userPostGroupTable.DataTable().row($(e).parents('tr'));
        row.remove().draw();
    }
    //弹出layer窗口
    function window1(icon, title, url, width, heigth, type) {
        var title2 = title;
        if (!isEmpty(icon)) {
            title2 = '<img src="' + icon + '" width="20"/>' + title;
        }
        layer.open({
            type: 2,
            title: title2,
            maxmin: true,
            shadeClose: false, //点击遮罩层关闭
            shade: [0.1, '#fff'],
            area: [width + "", heigth + ""],
            offset: ['10px'],
            fixed: false,
            content: url
        });
    }
</script>
</body>
</html>
